package com.google.code.irouter.plugin.detector;

import java.io.InputStream;
import java.util.List;

import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.util.SimpleNodeIterator;

import com.google.appengine.api.datastore.Link;
import com.google.code.irouter.batch.api.Detector;
import com.google.code.irouter.batch.api.DetectorResult;
import com.google.code.irouter.model.Guide;

public final class JuMeiYouPin extends Detector {

	@Override
	protected List<DetectorResult> resolve(Guide guide,
			InputStream inputStream, List<DetectorResult> result)
			throws Exception {
		return null;
	}

	@Override
	protected boolean isReconnect(Exception exception, boolean result) {
		if(ParserException.class.isInstance(exception))
			result = true;
		return result;
	}

	@Override
	protected List<DetectorResult> resolve(Guide guide, String text,
			List<DetectorResult> result) throws Exception {
		Parser parser = new Parser();
		parser.setInputHTML(text);
		NodeList nodeList = parser.parse(new NodeClassFilter(LinkTag.class));
		SimpleNodeIterator nodeIterator = nodeList.elements();
		HasAttributeFilter hasAttributeFilter = new HasAttributeFilter("class", "track_click");
		while(nodeIterator.hasMoreNodes()) {
			Node node = nodeIterator.nextNode();
			if(hasAttributeFilter.accept(node)) {
				if(node.toHtml().indexOf("img") < 0) {
					LinkTag linkTag = (LinkTag) node;
					if(linkTag.getStringText().trim().length() > 0) {						
						DetectorResult detectorResult = new DetectorResult();
						detectorResult.setMessage(linkTag.getStringText());
						detectorResult.setLink(new Link(guide.getResource().getValue() + linkTag.getLink()));
						detectorResult.setFixedLink(guide.getFixedLink());
						result.add(detectorResult);
					}					
				}				
			}
		}
		return result;
	}

	@Override
	protected LOAD_TYPE getLoadType() {
		return Detector.LOAD_TYPE.TEXT;
	}

}
